package com.example.demo.interceptor;

import com.example.demo.constant.Constants;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     log.info("登录拦截器校验");
     //返回true方形，返回false 表示拦截
        // 验证用户是否登录
//        HttpSession session=request.getSession(false);//没有session则创建一个sesion,false表示，没有session直接返回
//        if(session!=null&&session.getAttribute(Constants.SESSION_USER_KEY)!=null){
//            UserInfo userInfo=(UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
//            if (userInfo!=null&&userInfo.getId()>=0){
//                return true;
//            }
//        }
        HttpSession session=request.getSession();
        UserInfo userInfo=(UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
        if (userInfo!=null&&userInfo.getId()>=0){
            return true;
        }
        response.setStatus(401);//401表示未认证登录(表示http状态码,是一种规范)
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后");

    }
}
